<template>
  <div>
    <keep-alive>
      <div class="camera_outer">
        <video
          hidden="true"
          id="videoCamera"
          :width="videoWidth"
          :height="videoHeight"
        ></video>
        <canvas
          hidden="true"
          style="display: none"
          id="canvasCamera"
          :width="videoWidth"
          :height="videoHeight"
        ></canvas>
        <div v-if="imgSrc" class="img_bg_camera">
          <img id="drawImage" :src="imgSrc" alt="" class="tx_img" hidden="true" />
        </div>
      </div>
    </keep-alive>
    <van-tabbar route>
      <van-tabbar-item replace to="/record" icon="eye-o"
        >去识别</van-tabbar-item
      >
      <van-tabbar-item replace to="/group" icon="friends-o"
        >群组管理</van-tabbar-item
      >
      <van-tabbar-item replace to="/profile" icon="user-o"
        >个人信息</van-tabbar-item
      >
    </van-tabbar>
  </div>
</template>

<script>
function dataURItoBlob(dataURI) {
  var byteString = atob(dataURI.split(",")[1]);
  var mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ab], { type: mimeString });
}
export default {
  name: "TabBar",
  data() {
    return {
      videoHeight: 300,
      videoWidth: 300,
      imgSrc: null,
    };
  },
  mounted() {
    this.getCompetence();
  },
  methods: {
    setVideoActive(active) {
      let timerHandler = this.$store.state.record.timerHandler;
      if(active) {
        let thisVideo = this.$store.state.record.thisVideo;
        console.log(thisVideo);
        thisVideo.play();
        if(timerHandler != null) {
          clearInterval(timerHandler);
          this.$store.commit("record/setTimerHandler", {timerHandler: null});
        }
        timerHandler = setInterval(this.setImage, 2000);
        this.$store.commit("record/setTimerHandler", {timerHandler: timerHandler});
      } else {
        if(timerHandler != null) {
          clearInterval(timerHandler);
          this.$store.commit("record/setTimerHandler", {timerHandler: null});
        }
        let thisVideo = this.$store.state.record.thisVideo;
        thisVideo.pause();
      }
    },
    getCompetence() {
      console.log("getCompetence");
      var _this = this;
      this.thisCancas = document.getElementById("canvasCamera");
      this.thisContext = this.thisCancas.getContext("2d");
      this.thisVideo = document.getElementById("videoCamera");
      this.$store.commit("record/setVideoContext", {
        thisCancas: this.thisCancas,
        thisContext: this.thisContext,
        thisVideo: this.thisVideo,
      });
      let store = this.$store;
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia =
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(
              new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: 300,
          height: 300,
          transform: "scaleX(-1)",
        },
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function (stream) {
          // 旧的浏览器可能没有srcObject
          if ("srcObject" in store.state.record.thisVideo) {
            store.state.record.thisVideo.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。
            store.state.record.thisVideo.src =
              window.URL.createObjectURL(stream);
          }
          store.state.record.thisVideo.onloadedmetadata = function (e) {
            // _this.thisVideo.play();
          };
        })
        .catch((err) => {
          console.log(err);
        });
    },
    setImage() {
      // console.log("setImage, active: ", this.videoActive);
      // if(!this.videoActive) {
      //   return;
      // }
      console.log("Enter setImage");
      let _this = this;
      // 点击，canvas画图
      let thisContext = this.$store.state.record.thisContext;
      let thisVideo = this.$store.state.record.thisVideo;
      let thisCancas = this.$store.state.record.thisCancas;

      thisContext.drawImage(
        thisVideo,
        0,
        0,
        this.$store.state.record.videoWidth,
        this.$store.state.record.videoHeight
      );
      // 获取图片base64链接
      var image = thisCancas.toDataURL("image/jpeg");

      this.imgSrc = image;
      let userToken = this.$store.state.user.userToken;
      let groupToken = this.$store.state.group.selectedGroupToken;
      var blob = dataURItoBlob(image);
      this.$socket.emit("onImage", {
        imageBytes: blob,
        extension: "jpeg",
        userToken: userToken,
        groupToken: groupToken,
      });
      // this.send();
      // this.$emit("refreshDataList", this.imgSrc);
    },
  },
};
</script>
